#include "stdafx.h"
read_remo::read_remo(string inroot)
	{
		unsigned int i;
		string helpstring;
		root=inroot;
		FILE *help;
		names.push_back("REMO_precip1948_2005.dat");flag.push_back(0);filestart.push_back(1948);fileend.push_back(2005);fact.push_back(0.1);ins.push_back(help);
		names.push_back("REMO_temp1948_2005.dat");flag.push_back(0);filestart.push_back(1948);fileend.push_back(2005);fact.push_back(0.01);ins.push_back(help);
		names.push_back("Radiation_monthly1958_2004.dat");flag.push_back(0);filestart.push_back(1958);fileend.push_back(2004);fact.push_back(1);  ins.push_back(help);
		names.push_back("PRECIP_days1958_2004.dat");flag.push_back(0);filestart.push_back(1948);fileend.push_back(2005);fact.push_back(1);	ins.push_back(help);
		for(i=0;i<names.size();i++)
			{
				helpstring=root+names[i];
				if ((ins[i]=fopen(helpstring.c_str(),"r"))==NULL){
					   cout<<"Fail...open"<<helpstring<<endl;
					   flag[i]=0;
				}
				else{
					cout<<"OPEN..."<<helpstring<<endl;
					flag[i]=1;
				}
			}
	}
read_remo::~read_remo()
	{
		unsigned int i;
		for(i=0;i<ins.size();i++)   {
			if(flag[i]!=0){
				if( fclose( ins[i] ) )
					cout<<"Fail...close"<<root<<names[i]<<endl;
				}
			}
	}

float read_remo::read_weather_remo(int file, int year, int mon,double lati, double loni)
{
	int x1,x2,x3,x,pos=0;
	char s,s_ref=' ';
	float y;
	int lat,lon;
	
	if ((year<filestart[file])||(year>fileend[file]))err::err2("read_remo::read_weather_remo: year out of range");
	if((mon<1)||(mon>12))err::err2("read_remo::read_weather_remo: mon out of range");
	if((lati<30)||(lati>70))err::err2  ("read_remo::read_weather_remo: lat out of range");
	if((loni<-15)||(loni>30))err::err2  ("read_remo::read_weather_remo: lon out of range");

	lat=pos_lat(lati);
	lon=pos_lon(loni);

	x1=(year-filestart[file])*((180*300*6)+1)*12+(year-filestart[file])*5;
	x2=5+((180*300*6)+1)*(mon-1);
	x3=(lat-1)*300*6+(lon-1)*6;
	x=x1+x2+x3;pos=x;

	fseek (ins[file],x,SEEK_SET);
	do
	{
		s=fgetc(ins[file]);
		pos=pos+1;
	}
	while (s==s_ref);
	pos=pos-1;
	fseek (ins[file], pos,SEEK_SET);
	fscanf(ins[file],"%f",&y);
	
	return y*fact[file];
}